package com.tim.app.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;

import com.application.library.log.DLOG;
import com.application.library.runtime.event.EventManager;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;
import com.tim.app.R;
import com.tim.app.constant.AppKey;
import com.tim.app.constant.EventTag;
import com.tim.app.manager.ImagePickerManager;
import com.tim.app.util.PathUtil;
import com.tim.app.util.ToastUtil;

import java.io.File;

/**
 * 红米手机拍照应用会重启报错
 */
public class GetPhotoActivity extends BaseActivity {
    public static final int CODE_PICK_PHOTO = 998;// 从相册选图片
    public static final int CODE_TAKE_PHOTO = 999;// 拍照

    public static final String ACTION_PICK_PHOTO = "pick_photo";
    public static final String ACTION_TAKE_PHOTO = "take_photo";

    public static final String NEED_CROP = "need_crop";

    public String picturePath;

    private Uri mImageCaptureUri;

    private boolean needCrop = false;

    @Override
    protected void init(Bundle savedInstanceState) {
        super.init(savedInstanceState);
        if (savedInstanceState != null) {
            String image_path = savedInstanceState.getString("image_path");
            ImagePickerManager.ins().setImageUri(Uri.fromFile(new File(image_path)));
        }
    }

    @Override
    public void initView() {
        if (getIntent() != null) {
            needCrop = getIntent().getBooleanExtra(NEED_CROP, false);
//            if(android.os.Build.MODEL.contains("HM NOTE")){
//                needCrop = false;
//            }
            String action = getIntent().getAction();

            if (ACTION_PICK_PHOTO.equals(action)) {
                Intent intent = new Intent();
                /* 开启Pictures画面Type设定为image */
                intent.setType("image/*");
                /* 使用Intent.ACTION_GET_CONTENT这个Action */
                intent.setAction(Intent.ACTION_GET_CONTENT);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
                /* 取得相片后返回本画面 */
                startActivityForResult(intent, CODE_PICK_PHOTO);
            } else if (ACTION_TAKE_PHOTO.equals(action)) {
                try {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                    picturePath = RT.mLocalExternalPath.endsWith("/") ? RT.mLocalExternalPath : RT.mLocalExternalPath
//                            .concat("/") + "tmp_img_" + String.valueOf(System.currentTimeMillis()) + ".jpg";
//
//                    ContentValues values = new ContentValues();
//                    values.put(MediaStore.Images.Media.TITLE, picturePath);
//                    mImageCaptureUri = RT.application.getContentResolver().insert(
//                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
//                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
//
//                    // tmpPath = file.getPath();
//
//                    try {
//                        intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
//                        intent.putExtra("return-data", true);
//                    } catch (Exception e) {
//                        // e.printStackTrace();
//                    }
                    if (intent.resolveActivity(getPackageManager()) != null) {
                        mImageCaptureUri = ImagePickerManager.ins().getImageUri();
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
//                        intent.putExtra("return-data", true);
                    }
                    startActivityForResult(intent, CODE_TAKE_PHOTO);
                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                    ToastUtil.showToast(getString(R.string.floatshortcutchatgroupview_text_insert_sdcard));
                    finish();
                }
            }
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (mImageCaptureUri != null) {
            outState.putString("image_path", mImageCaptureUri.getPath());
        }
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        String image_path = savedInstanceState.getString("image_path");
        if (!TextUtils.isEmpty(image_path)) {
            ImagePickerManager.ins().setImageUri(Uri.fromFile(new File(image_path)));
        }
    }

    @Override
    public void initData() {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            EventManager.ins().sendEvent(EventTag.NOTIFY_CHOOSE_PHOTO, AppKey.CODE_CANCEL, 0, null);
            finish();
            return;
        }
        switch (requestCode) {
            case CODE_PICK_PHOTO:
                if (data != null && data.getData() != null) {
                    String path = "";
                    mImageCaptureUri = data.getData();
                    try {
//                    path = getRealPathFromURI(mImageCaptureUri);
                        path = PathUtil.getPath(this, mImageCaptureUri);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (needCrop && path != null) {
                        DLOG.d("photo", "path:" + path);
                        File file = new File(path);
                        gotoCropView(file.getAbsolutePath());
                    } else {
                        EventManager.ins().sendEvent(EventTag.NOTIFY_CHOOSE_PHOTO, 0, 0, path);
                        finish();
                    }
                } else {
                    return;
                }
                break;
            case CODE_TAKE_PHOTO: {
                String path = "";
                try {
                    path = PathUtil.getPath(this, mImageCaptureUri);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                File imageFile = new File(path);
                if (imageFile != null && imageFile.exists()) {
                    if (needCrop && path != null && !ImagePickerManager.ins().isFromGallery()) {
                        DLOG.d("photo", "path:" + path);
                        File file = new File(path);
                        gotoCropView(file.getAbsolutePath());
                    } else {
                        setResult(RESULT_OK);
                        finish();
                        EventManager.ins().sendEvent(EventTag.NOTIFY_CHOOSE_PHOTO, 0, 0, path);
                    }
                } else {
                    ToastUtil.showToast(getString(R.string.getphotoactivity_text_no_photo));
                    return;
                }
            }
            break;
        }
    }

    /**
     * 如果URI是以file://开头，就已经是真实路径了
     *
     * @param contentUri
     * @return
     */
    String getRealPathFromURI(Uri contentUri) {
        if (contentUri != null && contentUri.toString().startsWith("file://"))
            return contentUri.toString().substring("file://".length());

        String[] proj =
                {MediaStore.Images.Media.DATA};
        Cursor cursor = managedQuery(contentUri, proj, null, null, null);
        // 不要调用cursor的close
        if (cursor == null)
            return null;
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        String ret = cursor.getString(column_index);
        return ret;
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    @Override
    public void onClick(View v) {

    }

    public void gotoCropView(final String imagePath) {
        Dexter.checkPermission(new PermissionListener() {
            @Override
            public void onPermissionGranted(PermissionGrantedResponse response) {
                Intent intent = new Intent(GetPhotoActivity.this, ImageCropActivity.class);
                intent.putExtra(AppKey.IMAGE_PICK_PATH, imagePath);
                startActivity(intent);
                finish();
            }

            @Override
            public void onPermissionDenied(PermissionDeniedResponse response) {
                ToastUtil.showToast("权限被禁止，无法裁剪图片");
                finish();
            }

            @Override
            public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
                token.continuePermissionRequest();
            }
        }, Manifest.permission.READ_EXTERNAL_STORAGE);
    }
}
